"""
@author: xiangping
@contact: xiangpingbu@gmail.com
@time: 2019/12/29 3:10 下午
@file: run.py
@Desc:
"""

import importlib
import logging.config
from app import set_app


from flask import Flask
from flask.helpers import get_env

from app.configs import config_dict
from app.configs.logging_config import LOGGING
from app.controllers.filters.err_handler import ErrHandler
from app.exts import db, migrate, ma, scheduler, ironman_redis,mongo,influxdb,mysql_pool
from app.services.business.gaolu_biz_service import gaolu_clean_up
from app.services.sys_service import init_data_container


def register_extensions(app):
    db.init_app(app)
    migrate.init_app(app, db)
    ma.init_app(app)
    influxdb.init_app(app)
    mysql_pool.init_app(app)
    ironman_redis.init(app)

    # if ironman_redis.acquire_redis_lock("schedule","schedule"):
    #     scheduler.init_app(app)
    #     if app.config['SCHEDULE_SWITCH']:
    #         scheduler.start()
    #         logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING)
    #     ironman_redis.release_redis_lock("schedule","schedule")




def register_blueprints(app):
    from app import controllers
    for name in controllers.__all__:
        bp = getattr(importlib.import_module(f'app.controllers.{name}'), 'bp', None)
        if bp is not None:
            app.register_blueprint(bp)


def register_error_handler(app):
    app.register_error_handler(Exception, ErrHandler.handler)


def register_cmds(app):
    pass


def register_logging(app):
    app.logger.name = 'iron_man'
    # logging.config.dictConfig(LOGGING)


def register_cache(app):
    ironman_redis.init(app)


def register_data_container(app):
    is_persist = app.config['PERSIST_CONTAINER_ENABLE']
    is_loaded = app.config['CONTAINER_IS_LOADED']
    init_data_container(app, is_loaded=is_loaded, is_persist=is_persist)


def register_clean_up(app):
    start_time = app.config['GAOLU_CLEAN_START']
    end_time = app.config['GAOLU_CLEAN_END']
    gaolu_clean_up(start_time, end_time)

def register_mongodb(app):
    mongo.init_app(app, uri="mongodb://192.168.40.214:20017/ironman")


def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config_dict[get_env()])

    with app.app_context():
        register_logging(app)
        register_extensions(app)
        # register_cache(app)
        register_blueprints(app)
        register_error_handler(app)
        register_cmds(app)
        register_data_container(app)
        # register_mongodb(app)
        # register_cache(app)
        if app.config['SCHEDULE_SWITCH'] and app.config['GAOLU_SIMULATION_ENABLED']:
            register_clean_up(app)

    set_app(app)
    return app


app = create_app()

if app.config['ENABLE_KAFKA']:
    from app.services import kafka_service
    kafka_service


if __name__ == "__main__":
    # app = application.create_app(env, NACOS_ENABLE=os.environ.get(
    #     'NACOS_ENABLE'))  # from .main.controller import controller as main_blueprint

    app.run(host='0.0.0.0', port=8088, debug=True, use_reloader=False, threaded=True)
